import {onMounted, provide, ref} from 'vue'
import {AccessRecord, HotDreamVideo, Movie} from '@/data/Dream'
import {accessRecordsDB, movieDB} from '@/data/lowdb.ts'
import {sortByLastAccessTime} from '@/data/access_records.ts'
import {openVideoDefault} from '@/utils/utils.ts'

export function useVideo() {
    const videos = ref<HotDreamVideo[]>([])
    const videoAccessRecords = ref<Map<string, AccessRecord>>()
    provide('videoAccessRecords', videoAccessRecords)

    onMounted(() => {
        videoAccessRecords.value = new Map<string, AccessRecord>(
            Object.entries(accessRecordsDB.get('videoAccessRecords').value()),
        )
        const movies: Movie[] = movieDB.read().value()
        for (let movie of movies) {
            for (let video of movie.dreamVideos) {
                if (video.images.length === 0) continue
                let hotVideo: HotDreamVideo = <HotDreamVideo>{}
                Object.assign(hotVideo, video)
                hotVideo.movie = movie
                videos.value.push(hotVideo)
            }
        }
        videos.value.sort((a, b) => {
            return sortByLastAccessTime(
                videoAccessRecords.value.get(a.video), videoAccessRecords.value.get(b.video),
            )
        })
    })
    function openHotVideo(video: HotDreamVideo) {
        openVideoDefault(video.movie, video.video, videoAccessRecords.value)
    }
    return {
        videos,
        openHotVideo
    }
}